<template>
  <div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12" style="padding-right: 30px">
          <div class="el-inpit-width">
            <el-form-item label="商品名称" prop="name">
              <el-input
                v-model="ruleForm.name"
                clearable
                placeholder="请输入商品名称"
              ></el-input>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12" style="padding-right: 30px">
          <div>
            <el-form-item label="商品价格" prop="price">
              <el-input
                v-model="ruleForm.price"
                clearable
                placeholder="请输入商品价格"
              ></el-input>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <!-- 第二行 -->
      <el-row :gutter="10">
        <el-col :span="12" style="padding-right: 30px">
          <div class="el-inpit-width">
            <el-form-item label="商品描述" prop="desc">
              <el-input
                maxlength="30"
                placeholder="请输入商品描述"
                clearable
                autosize
                v-model="ruleForm.desc"
                show-word-limit
              ></el-input>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12" style="padding-right: 30px">
          <div>
            <el-form-item label="商品服务" prop="severs">
              <el-select
                class="max-width"
                clearable
                v-model="ruleForm.severs"
                multiple
                placeholder="请选择商品服务"
              >
                <el-option
                  v-for="(item, index) in severList"
                  :key="index"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <!-- 第三行 -->
      <el-row :gutter="10">
        <el-col :span="12" style="padding-right: 30px">
          <div class="el-inpit-width">
            <el-form-item label="商品规格" prop="specifications">
              <el-select
                class="max-width"
                clearable
                v-model="ruleForm.specifications"
                multiple
                placeholder="请选择商品规格"
              >
                <el-option
                  v-for="(item, index) in specificationsList"
                  :key="index"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12" style="padding-right: 30px">
          <div>
            <el-form-item label="商品类别" prop="type">
              <el-select
                class="max-width"
                clearable
                v-model="ruleForm.type"
                placeholder="请选择商品类别"
              >
                <el-option
                  v-for="(item, index) in typeList"
                  :key="index"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="24" style="padding-right: 30px">
          <div class="el-inpit-width">
            <el-form-item label="商品封面图" prop="coverImg">
              <!-- 展示图片相关 -->
              <uploadImg
                :limit="1"
                ref="coverImg"
                :isUpdate="rawId ? true : false"
                :keyName="'coverImg'"
              ></uploadImg>
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="10">
        <el-col :span="24" style="padding-right: 30px">
          <div class="el-inpit-width">
            <el-form-item label="商品轮播图" prop="lunboImageUrls">
              <!-- 展示图片相关 -->
              <uploadImg
                :limit="5"
                ref="upload"
                :isUpdate="rawId ? true : false"
                :keyName="'lunboImageUrls'"
              ></uploadImg>
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="10">
        <el-col :span="24" style="padding-right: 30px">
          <div class="el-inpit-width">
            <el-form-item label="商品详情图" prop="introduceUrl">
              <!-- 展示图片相关 -->
              <uploadImg
                :limit="20"
                ref="introduceUrl"
                :isUpdate="rawId ? true : false"
                :keyName="'introduceUrl'"
              ></uploadImg>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-form-item style="text-align: center">
        <el-button @click="back()">返回</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">{{
          rawId ? "保存修改" : "立即创建"
        }}</el-button>
        <el-button v-show="!rawId" @click="resetForm('ruleForm')"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
// 引入选择图片组件
import uploadImg from "../../util/tool/upload";
import { getNowTime, getCoolePage, updateColl } from "../../util/time.js";

export default {
  components: {
    uploadImg: uploadImg,
  },
  data() {
    return {
      rawId: "",
      ruleForm: {
        // 名称
        name: "",
        // 价格
        price: "",
        // 描述
        desc: "",
        // 服务项目
        severs: [],
        // 规格
        specifications: [],
        // 类别
        type: "",
        // 封面图
        coverImg: [],
        // 轮播图片
        lunboImageUrls: [],
        // 介绍图
        introduceUrl: [],
        // 上架时间
        launchTime: "",
        // 销量
        salesVolume: 0,
      },
      rules: {
        name: { required: true, message: "请输入商品名称", trigger: "blur" },
        price: { required: true, message: "请输入商品价格", trigger: "blur" },
        desc: { required: true, message: "请输入商品描述", trigger: "blur" },
        severs: { required: true, message: "请输入商品服务", trigger: "blur" },
        specifications: {
          required: true,
          message: "请输入商品规格",
          trigger: "blur",
        },
        type: {
          required: true,
          message: "请输入商品类别",
          trigger: "blur",
        },
        coverImg: {
          required: true,
          message: "请选择商品封面图片",
          trigger: "blur",
        },
        lunboImageUrls: {
          required: true,
          message: "请选择商品轮播图片",
          trigger: "blur",
        },
        introduceUrl: {
          required: true,
          message: "请选择商品介绍图片",
          trigger: "blur",
        },
      },
      // 商品服务
      severList: ["正品保障", "急速退款", "运费险", "7天无理由退款"],
      // 商品规格
      specificationsList: ["XS", "S", "M", "L", "XL", "XXL", "XXXL"],
      // 商品类别
      typeList: [
        "办公",
        "家电",
        "服饰",
        "日用",
        "蔬果",
        "运动",
        "书籍",
        "文具",
      ],
    };
  },
  mounted() {
    // 根据路由获取传递过来的参数
    this.rawId = this.$route.query.rawId;
    if (this.rawId) {
      this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      // 如果有商品id根据商品id获取商品详情
      this.getRawInfo();
    }
  },
  methods: {
    // 返回
    back() {
      //返回上一层
      // this.$router.go(-1);
      this.$router.push("/personal/productList")
    },
    // 如果有商品id根据商品id获取商品详情
    getRawInfo() {
      // 根据id查询数据库数据
      getCoolePage("books", 1, 10, { _id: this.rawId }).then((res) => {
        this.$loading().close();
        this.ruleForm = res.data[0];
        // 赋值封面图
        this.$refs.coverImg.setImgUrls(this.ruleForm.coverImg);
        // 赋值轮播图
        this.$refs.upload.setImgUrls(this.ruleForm.lunboImageUrls);
        // 赋值介绍图
        this.$refs.introduceUrl.setImgUrls(this.ruleForm.introduceUrl);
      });
    },
    // 提交方法
    async submitForm(formName) {
      // 封面图路径
      let coverImg = this.$refs.coverImg.retImgUrls();
      // 轮播图路径
      let lunboImageUrls = this.$refs.upload.retImgUrls();
      // 介绍图路径
      let introduceUrl = this.$refs.introduceUrl.retImgUrls();
      // 读取封面图路径
      this.ruleForm.coverImg = coverImg;
      // 读取轮播u路径
      this.ruleForm.lunboImageUrls = lunboImageUrls;
      // 读取介绍图路径
      this.ruleForm.introduceUrl = introduceUrl;

      console.log(this.ruleForm);

      // return;

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          // 等待图片上传成功
          this.uploadImgAll(coverImg, lunboImageUrls, introduceUrl).then(() => {
            if (this.rawId) {
              this.update();
            } else {
              // 保存数据方法
              this.preservation();
            }
          });
        } else {
          this.$message("请把信息填写完整");
          return false;
        }
      });
    },
    // 重置方法
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 批量上传图片
    uploadImgAll(coverImg, lunboImageUrls, introduceUrl) {
      return new Promise((resolve) => {
        this.uploadIaage("coverImg", coverImg).then(() => {
          this.uploadIaage("lunboImageUrls", lunboImageUrls).then(() => {
            this.uploadIaage("introduceUrl", introduceUrl).then(() => {
              resolve(true);
            });
          });
        });
      });
    },
    // 图片异步上传
    async uploadIaage(dataName, imgList) {
      this.ruleForm[dataName] = [];
      // 异步上传图片
      for (const file of imgList) {
        if (file.fileID) {
          this.ruleForm[dataName].push(file);
        } else {
          // 等待上一张图片上传成功后再上传第二章图片
          let imgURL = await this.$wxApp.uploadFile({
            // 云存储的路径
            cloudPath: `bookImg/pcImgList/${new Date().getTime()}_${file.name}`,
            // 需要上传的文件，File 类型
            filePath: file.raw,
          });
          // 获取到上传的图片id后根据id获取真实图片路径
          if (imgURL.fileID) {
            // 根据已上传的图片id获取下载地址
            await this.$wxApp
              .getTempFileURL({
                fileList: [imgURL.fileID],
              })
              .then((res) => {
                res.fileList.forEach((el) => {
                  if (el.code === "SUCCESS") {
                    this.ruleForm[dataName].push({
                      url: el.tempFileURL,
                      fileID: imgURL.fileID,
                    });
                  }
                });
              });
          }
        }
      }
      return this.ruleForm[dataName];
    },
    // 批量删除图片
    removeAllImage() {
      // 从云存储中删除封面图片
      let coverIds = this.ruleForm.coverImg.map((item) => item.fileID);
      let lunboIds = this.ruleForm.lunboImageUrls.map((item) => item.fileID);
      let introduceIds = this.ruleForm.introduceUrl.map((item) => item.fileID);
      return new Promise((resolve) => {
        this.byIdDeleteImage(coverIds).then(() => {
          this.byIdDeleteImage(lunboIds).then(() => {
            this.byIdDeleteImage(introduceIds).then(() => {
              resolve(true);
            });
          });
        });
      });
    },
    // 根据文件id删除图片，参数为文件id组成的数据
    byIdDeleteImage(ids) {
      // 删除数据库中存储的图片文件
      return this.$wxApp.deleteFile({
        fileList: ids,
      });
    },
    // 保存数据方法
    preservation() {
      // 获取当前时间
      this.ruleForm.launchTime = getNowTime();
      // 添加数据
      this.$wxApp
        .database()
        .collection("books")
        .add(this.ruleForm)
        .then((res) => {
          if (!res.code) {
            // 添加成功取消loading框
            this.$loading().close();
            // 提示添加成功
            this.$confirm("添加成功!", "提示", {
              confirmButtonText: "确定",
              type: "success",
              showCancelButton: false,
            }).then(() => {
              this.$router.go(-1);
            });
          } else {
            this.$loading().close();
            this.$message.error("添加失败，请重试");
          }
        });
    },
    // 更新方法
    update() {
      delete this.ruleForm._id;
      delete this.ruleForm._openid;
      updateColl("books", this.rawId, this.ruleForm).then(() => {
        // 添加成功取消loading框
        this.$loading().close();
        this.$confirm("修改成功!", "提示", {
          confirmButtonText: "确定",
          type: "success",
          showCancelButton: false,
        }).then(() => {
          this.$router.go(-1);
        });
      });
    },
  },
};
</script>

<style scoped>
.el-inpit-width {
  padding-right: 30px;
}
.max-width {
  width: 100%;
}
.descimgBox {
  display: flex;
  flex-wrap: wrap;
  margin-right: 10px;
  gap: 10px;
}
.descimgBox > .imgcontent {
  position: relative;
  width: 110px;
  height: 110px;
}
.descimgBox > .imgcontent > img {
  width: 100%;
  height: 100%;
  border: 1px solid #c7c7c7;
  border-radius: 2px;
}
.imagedeleteicon {
  position: absolute;
  right: -6px;
  top: -4px;
  font-size: 20px;
  color: #f56c6c;
  background-color: white;
  border-radius: 50%;
}
</style>

<style>
.el-upload-list,
.el-upload-list--picture {
  display: none !important;
}
</style>

